package com.itany.boot.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.boot.constant.DictConstant;
import com.itany.boot.dao.GoldPointsMapper;
import com.itany.boot.dao.UserMapper;
import com.itany.boot.entity.GoldPoints;
import com.itany.boot.entity.GoldPointsExample;
import com.itany.boot.entity.User;
import com.itany.boot.exception.RequestParameterErrorException;
import com.itany.boot.service.GoldPointsService;
import com.itany.boot.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class GoldPointsServiceImpl implements GoldPointsService {
    @Autowired
    private GoldPointsMapper goldPointsMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageInfo<GoldPoints> findPage(String UserId, String pageNo, String pageSize) {
        if(ParameterUtil.isNull(pageNo)){
            pageNo= DictConstant.GOLD_POINTS_TYPE_DEFAULT_PAGE_NO;
        }
        if(ParameterUtil.isNull(pageSize)){
            pageSize= DictConstant.GOLD_POINTS_TYPE_DEFAULT_PAGE_SIZE;
        }
        GoldPointsExample example = new GoldPointsExample();
//        传入id查找当前用户
        example.or()
                .andUserIdEqualTo(Integer.valueOf(UserId));
//        按时间排序
        example.setOrderByClause("create_date DESC");
//        分页插件
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
//        传入查询条件，存到集合
        List<GoldPoints> goldPoints = goldPointsMapper.selectByExample(example);
//          封装分页对象
        PageInfo<GoldPoints> goldPointsPage = new PageInfo<>(goldPoints);
        return goldPointsPage;

    }

    @Override
    public User showNumber(String UserId) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(UserId)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        User user=userMapper.selectByPrimaryKey(Integer.parseInt(UserId));
        GoldPointsExample example = new GoldPointsExample();
        example.or()
                .andUserIdEqualTo(Integer.valueOf(UserId));
        List<GoldPoints> goldPoints = goldPointsMapper.selectByExample(example);
        for (GoldPoints sum : goldPoints) {
            user.setAllPoint(user.getAllPoint()+sum.getPointCount());
            user.setAllGold(user.getAllGold()+sum.getGoldCount());
        }
        System.out.println("查询的用户ID：" + user.getId() + "，查询到的积分：" + user.getAllPoint());
        return user;
    }


    @Override
    public void buyGold(String UserId, String point) throws RequestParameterErrorException {
        // 参数校验
        if (ParameterUtil.isNull(UserId) || ParameterUtil.isNull(point)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        // 查询用户信息
        User user = showNumber(UserId);
        if (user == null) {
            throw new RequestParameterErrorException("用户不存在");
        }
        Integer userId;
        Integer pointCount;
        try {
            userId = Integer.parseInt(UserId);
            pointCount = Integer.parseInt(point);
        } catch (NumberFormatException e) {
            throw new RequestParameterErrorException("用户ID或积分参数格式错误");
        }

        // 校验积分是否为正数且是10的倍数
        if (pointCount <= 0 || pointCount % 10 != 0) {
            throw new RequestParameterErrorException("兑换积分必须为正数且是10的倍数");
        }


        System.out.println("查询的用户ID：" + userId + "，查询到的积分：" + user.getAllPoint());
        System.out.println("用户当前积分：" + user.getAllPoint());
        System.out.println("本次兑换积分：" + pointCount);

        // 校验用户积分是否充足
        if (user.getAllPoint() < pointCount) {
            throw new RequestParameterErrorException("用户积分不足，无法兑换");
        }

        // 计算可兑换的金币数量
        Integer goldCount = pointCount / 10;

        // 更新用户的积分和金币
        user.setAllPoint(user.getAllPoint() - pointCount);
        user.setAllGold(user.getAllGold() + goldCount);
        userMapper.updateByPrimaryKeySelective(user);

        // 记录积分金币变动记录
        GoldPoints goldPoints = new GoldPoints();
        goldPoints.setUserId(userId);
        goldPoints.setPointCount(-pointCount);
        goldPoints.setInfo(user.getNickname()+"兑换了"+pointCount+"积分");
        goldPoints.setCreateDate(new Date());
        goldPointsMapper.insertSelective(goldPoints);
        GoldPoints goldPoints1 = new GoldPoints();
        goldPoints1.setUserId(userId);
        goldPoints1.setGoldCount(goldCount);
        goldPoints1.setInfo(user.getNickname()+"兑换积分获得"+goldCount+"金币");
        goldPoints1.setCreateDate(new Date());
        goldPointsMapper.insertSelective(goldPoints1);
    }
}
